﻿// $Id: ServiceProxy.cs 11 2008-08-20 15:24:25Z jkingry $

namespace Mithril.Server
{
    using System;
    using System.IO;
    using System.Net;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;

    [DataContract]
    class ServiceResult
    {
        [DataMember(Name="server_key")]
        public string ServerKey { get; set; }
        [DataMember(Name = "ip_address")]
        public string IpAddress { get; set; }
    }

    class ServiceProxy
    {
        WebClient client = new WebClient();

        public ServiceProxy() : this(Properties.Settings.Default.ServiceBaseAddress)
        {
        }

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServiceResult));


        public ServiceProxy(string baseAddress)
        {
            client.BaseAddress = baseAddress;
        }

        public ServiceResult Create(string account, string name)
        {
            using (Stream s = client.OpenRead(
                String.Format("create?account={0}&name={1}",
                    Uri.EscapeUriString(account),
                    Uri.EscapeUriString(name))))
            {
                return (ServiceResult) serializer.ReadObject(s);
            }
        }

        public void Delete(string account, string server)
        {
            using (Stream s = client.OpenRead(
                String.Format("delete?account={0}&server={1}",
                    Uri.EscapeUriString(account),
                    Uri.EscapeUriString(server))))
            using(StreamReader r = new StreamReader(s))
            {
                r.ReadToEnd();
            }
        }

        public ServiceResult Update(string account, string server, bool active)
        {
            using (Stream s = client.OpenRead(
                String.Format("update?account={0}&server={1}&active={2}",
                    Uri.EscapeUriString(account),
                    Uri.EscapeUriString(server),
                    active)))
            {
                return (ServiceResult)serializer.ReadObject(s);
            }
        }
    }
}
